import datetime
from django.db import transaction
from rest_framework import permissions
from rest_framework.views import APIView
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from apps.system.models import Upload, SystemLog, Option
from apps.system.serializers import OptionSerializer
from .serializers import CouponSerializer
from .models import Coupon, CouponCeleryTask
from .filters import CouponFilter
from .tasks import start_issue_coupon, end_issue_coupon


# Create your views here.

class CouponsViewSet(CustomModelViewSet):
    '''优惠卷'''
    permission_classes = [permissions.IsAdminUser]
    queryset = Coupon.objects.filter(delete=False)
    serializer_class = CouponSerializer

    def filter_queryset(self, queryset):
        f = CouponFilter(self.request.GET, queryset=self.queryset)
        return f.qs

    def create(self, request, *args, **kwargs):
        try:
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid(raise_exception=True):
                # 保存优惠卷
                coupon = serializer.save(user=self.request.user)
                # 定时任务1：从未开始 -->  发放中
                # 2020-09-03 05:30:00
                start_issue_time = datetime.datetime.utcfromtimestamp(coupon.start_time.timestamp())
                start_issue_coupon_task_id = start_issue_coupon.apply_async(args=[coupon.id], eta=start_issue_time).id
                # 定时任务2：从发放中 -->  已结束
                end_issue_time = datetime.datetime.utcfromtimestamp(coupon.end_time.timestamp())
                end_issue_coupon_task_id = end_issue_coupon.apply_async(args=[coupon.id], eta=end_issue_time).id

                # 保存定时任务id
                CouponCeleryTask.objects.create(coupon=coupon, start_issue_coupon_task_id=start_issue_coupon_task_id,
                                                end_issue_coupon_task_id=end_issue_coupon_task_id)

                return response_ok()
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                instance = self.get_object()
                instance.delete = True
                instance.save()
                SystemLog.objects.add_log(self.request.user, SystemLog.DELETE, '删除优惠卷Coupon(id=%s)信息' % instance.id)
        except Exception as e:
            return response_error(str(e))
        return response_ok()
